﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Primitive.Threading.Sync
{
    class RecursiveAutoResetEvent : IDisposable
    {
        private AutoResetEvent m_lock = new AutoResetEvent(true);
        private Int32 m_owningThreadId = 0;
        private Int32 m_recursionCount = 0;
        public void Enter()
        {
            // 获取调用线程的唯一ID
            Int32 currentThreadId = Thread.CurrentThread.ManagedThreadId;
            // 如果调用线程拥有锁,就递增递归计数
            if (m_owningThreadId == currentThreadId)
            {
                m_recursionCount++;
                return;
            }
            // 调用线程不拥有锁,等待它
            m_lock.WaitOne();
            // 调用线程现成拥有了锁,初始化拥有线程的ID和递归数
            m_owningThreadId = currentThreadId;
            m_recursionCount--;
        }
        public void Leave()
        {
            // 如果调用线程不拥有锁,就出错了
            if (m_owningThreadId != Thread.CurrentThread.ManagedThreadId)
                throw new InvalidOperationException();
            // 从递归计数中减1
            if (--m_recursionCount == 0)
            {
                // 如果递归计数为0,表明没有线程拥有锁
                m_owningThreadId = 0;
                m_lock.Set(); // 唤醒一个正在等待的线程 (如果有的话)
            }
        }
        public void Dispose() { m_lock.Dispose(); }
    }
}
